const DB = require('../core/DB')
const {
    Op
} = require('sequelize')

const {
    uPutToken,
    uMd5
} = require('../core/utils')

const Jwt = require('jsonwebtoken') // 解析 token
const {
    jwt_config
} = global.config
const secretKey = jwt_config.serect


class AdminController {
    /* ------------------------- ok 搜索管理员 -------------------------------*/
    async searchAdmin(ctx) {
        // 参数
        let {
            page = 1, size = 10, id, status, name
        } = ctx.query

        page = Number(page)
        size = Number(size)

        let params = {}
        if (id) params.id = id
        if (status) params.status = status
        if (name) params.name = {
            [Op.like]: `%${name}%`
        }

        const {
            count,
            rows
        } = await DB.admin.findAndCountAll({
            attributes: {
                exclude: ['password']
            },
            where: params,
            offset: (page - 1) * size,
            limit: size
        })

        const data = {
            rows,
            meta: {
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }

        // if (count) {
        global.Response.success(ctx, undefined, data)
        // } else {
        //     global.Response.null(ctx)
        // }
    }

    /* ------------------------- ok 获取管理员信息 -------------------------------*/
    async getAdminInfo(ctx) {
        const {
            id
        } = ctx.query
        const user = await DB.admin.findByPk(id, {
            attributes: {
                exclude: ['password']
            }
        })
        if (user) {
            global.Response.success(ctx, undefined, user)
        } else {
            global.Response.null(ctx)
        }
    }

    /* ------------------------- ok 获取用户列表 -------------------------------*/
    async listAdmin(ctx) {
        // 参数
        let {
            page = 1, size = 10
        } = ctx.query

        page = Number(page)
        size = Number(size)

        const {
            count,
            rows
        } = await DB.admin.findAndCountAll({
            attributes: {
                exclude: ['password']
            },
            offset: (page - 1) * size,
            limit: size
        })

        const data = {
            rows,
            meta: {
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }

        if (count) {
            global.Response.success(ctx, undefined, data)
        } else {
            global.Response.null(ctx)
        }
    }

    /* ------------------------- ok 管理员登录 -------------------------------*/
    async loginAdmin(ctx) {
        const {
            email = '',
            account = '',
            password
        } = ctx.request.body

        const admin = await DB.admin.findOne({
            where: {
                // 可选择邮箱登录或者账号登录
                [Op.or]: [{ email }, { account }],
                password: uMd5(password),
            }
        })
        if (admin) {
            let lastLoginAt = await admin.get('updatedAt')
            // 更新登录时间
            admin.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
            await admin.save()


            const data = {
                user: {
                    userId: admin.id,
                    name: admin.name,
                    email: admin.email,
                    account: admin.account,
                    auth: admin.auth,
                    lastLoginAt
                },
                token: uPutToken(admin.id, admin.auth)
            }
            global.Response.success(ctx, '登录成功', data)
        } else {
            global.Response.fail(ctx, '账号或密码错误')
        }
    }

    /* ------------------------- ok 管理员令牌登录 -------------------------------*/
    async loginToken(ctx) {
        try {
            const {token} = ctx.request.body
            const decode = Jwt.verify(token, secretKey)

            const admin = await DB.admin.findByPk(decode.uid)
            let lastLoginAt = await admin.get('updatedAt')
            // 更新登录时间
            admin.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
            await admin.save()

            const data = {
                user: {
                    userId: admin.id,
                    name: admin.name,
                    email: admin.email,
                    auth: admin.auth,
                    lastLoginAt
                },
                token: uPutToken(admin.id)
            }
            global.Response.success(ctx, '登录成功', data)
        } catch (error) {
            global.Response.fail(ctx, '令牌失效')
        }

    }



    /* ------------------------- ok 更新管理员信息 -------------------------------*/
    async updateInfo(ctx) {
        const {
            id,
            name,
            account,
            password,
            status,
            auth,
        } = ctx.request.body

        const admin = await DB.admin.findByPk(id)

        if (name) admin.name = name
        if (account) admin.name = account
        if (status != undefined) admin.status = status
        if (auth) admin.auth = auth
        if (password) admin.password = uMd5(password)
        admin.updated_at = global.Moment().format('YYYY-MM-DD HH:mm:ss')
        admin.save()

        global.Response.success(ctx, '更新成功')
    }

}

module.exports = new AdminController